package com.upupwe.raspberry.app.update;

import com.upupwe.raspberry.app.utils.RxBus;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Timeout;
import timber.log.Timber;

public class ApkResponseBody extends ResponseBody {

    private Response originalResponse;//原responsebody

    public ApkResponseBody(Response originalResponse) {
        this.originalResponse = originalResponse;
    }

    /**
     * 返回内容类型
     *
     * @return
     */
    @Override
    public MediaType contentType() {
        return originalResponse.body().contentType();
    }

    /**
     * 内容总长度
     * @return
     */
    @Override
    public long contentLength() {
        return originalResponse.body().contentLength();
    }

    /**
     * 返回缓存源,类似于io中的BufferedReader
     *
     * @return
     */
    @Override
    public BufferedSource source() {

        return Okio.buffer(new ForwardingSource(originalResponse.body().source()) {
            long totalRead = 0;

            //返回读取的长度
            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                totalRead += bytesRead == -1 ? 0 : bytesRead;
                Timber.i("本次下载：" + bytesRead);
                Timber.i("总共下载：" + totalRead);
                RxBus.getDefault().post(new ApkLoadingBean(contentLength(), totalRead));
                return bytesRead;
            }

            @Override
            public Timeout timeout() {
                return super.timeout();
            }

            @Override
            public void close() throws IOException {
                super.close();
            }

            @Override
            public String toString() {
                return super.toString();
            }
        });
    }
}
